import json

from flask import Blueprint, request, jsonify

from apps.path.pathService import get_last_position_service, trace_back_service, getTrailerPath, \
    returnGpsByPathIdService, insert_path, path_end_action

from . import path_bp
from ..gpsAndPathUtils import deal_cors


@path_bp.route('/path/getLastPosition', methods=["GET"])
def get_last_position():
    return get_last_position_service(request.args.get("trailer_ID"))


@path_bp.route('/path/traceBack', methods=["GET"])
def trace_back():
    return trace_back_service(request.args.get("trailer_ID"))


@path_bp.route('/path/getPathsByTrailerID', methods=["GET"])
def getPathsByTrailerID():
    return getTrailerPath(request.args.get("trailer_ID"))


@path_bp.route('/path/returnGpsByPathID', methods=["GET"])
def returnGpsByPathIdView():
    return returnGpsByPathIdService(request.args.get("path_ID"))


@path_bp.route('/path/addNewPath', methods=["POST"])
def addNewPath():
    params_data = json.loads(request.get_data())
    insert_path(params_data["path_ID"],
                [params_data["gps1"], params_data["gps2"]],
                params_data["start_time"],
                params_data["trailer_ID"])
    return deal_cors(jsonify({"code": 200, "data": "ok"}))


@path_bp.route('/path/pathEnd', methods=["POST"])
def pathEnd():
    params_data = json.loads(request.get_data())
    path_end_action(
        params_data["path_ID"],
        [params_data["gps1"], params_data["gps2"]],
        params_data["end_time"],
        params_data["trailer_ID"]
    )
    return deal_cors(jsonify({"code": 200, "data": "ok"}))